<template>
  <div class="system-user-dialog-container">
    <el-dialog @close="closeDialog()" :title="state.dialog.title" v-model="state.dialog.isShowDialog" width="500px">
      <el-form ref="userDialogFormRef"
               :rules="state.dialog.rules"
               :model="state.ruleForm"
               size="default"
               label-width="90px">

        <el-form-item label="标题" prop="title">
          <el-input v-model="state.ruleForm.title" placeholder="请输入标题" clearable></el-input>
        </el-form-item>

        <el-form-item label="标签" prop="typeId">
          <el-select
              v-model="state.ruleForm.typeId"
              placeholder="请选择标签"
              maxlength="150"
              filterable
              clearable>
            <el-option
                v-for="item in state.tags"
                :key="item.value"
                :label="item.text"
                :value="item.value"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="作者" prop="userId">
          <el-select
              v-model="state.ruleForm.userId"
              placeholder="请选择标签"
              maxlength="150"
              filterable
              clearable>
            <el-option
                v-for="item in state.users"
                :key="item.user.id"
                :label="item.user.name"
                :value="item.user.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="简介" prop="introduction">
          <el-input v-model="state.ruleForm.introduction" type="textarea" placeholder="请输入简介" clearable></el-input>
        </el-form-item>

        <el-form-item label="成果链接">
          <el-input v-model="state.ruleForm.achievementlink" placeholder="请输入成果链接" clearable></el-input>
        </el-form-item>

        <el-form-item label="封面">
          <el-upload
              ref="img"
              :limit="1"
              :on-change="handleImgChange"
              :on-exceed="handleImgExceed"
              :file-list="state.imgList"
              :on-preview="handlePictureCardPreview"
              :auto-upload="false"
              list-type="picture-card">
            <el-icon>
              <Plus/>
            </el-icon>
          </el-upload>
          <el-dialog v-model="dialogVisible">
            <img w-full :src="state.imgList[0].url" alt="Preview Image"/>
          </el-dialog>
        </el-form-item>

        <el-form-item label="附件">
          <el-upload
              ref="file"
              :limit="1"
              :on-change="handleFileChange"
              :on-exceed="handleFileExceed"
              :file-list="state.fileList"
              :auto-upload="false"
              style="width:400px"
              multiple>
            <el-button type="primary">上传成果附件</el-button>
          </el-upload>
        </el-form-item>

      </el-form>
      <template #footer>
				<span class="dialog-footer">
					<el-button @click="onCancel" size="default">取 消</el-button>
					<el-button type="primary" @click="onSubmit(userDialogFormRef)" size="default">{{
              state.dialog.submitTxt
            }}</el-button>
				</span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts" name="systemUserDialog">
import {reactive, ref} from "vue";
import {ElMessage, FormInstance, genFileId, UploadInstance, UploadProps, UploadRawFile} from "element-plus";
import {Plus} from "@element-plus/icons-vue";
import {updateAchievement, uploadAchievement} from "/@/views/achievement/achievement";
import qiniu from "/@/utils/qiniu.js";
// 定义子组件向父组件传值/事件
const emit = defineEmits(["refresh"]);
const img = ref<UploadInstance>();
const file = ref<UploadInstance>();

const handleImgChange: UploadProps["onChange"] = (file) => {
  state.img = file;
};
const handleFileChange: UploadProps["onChange"] = (file) => {
  state.file = file;
};
const handleImgExceed: UploadProps["onExceed"] = (files) => {
  img.value!.clearFiles();
  const file = files[0] as UploadRawFile;
  file.uid = genFileId();
  img.value!.handleStart(file);
};
const handleFileExceed: UploadProps["onExceed"] = (files) => {
  file.value!.clearFiles();
  const newFile = files[0] as UploadRawFile;
  newFile.uid = genFileId();
  file.value!.handleStart(newFile);
  console.log(state.fileList);
};


// 定义变量内容
const userDialogFormRef = ref<FormInstance>();
const dialogVisible = ref(false);
const handlePictureCardPreview: UploadProps["onPreview"] = () => {
  dialogVisible.value = true;
};
const state = reactive({
  tags: [],
  users: [],
  ruleForm: {
    id: "",
    userId: "",
    title: "",
    typeId: "",
    introduction: "",
    posterlink: "",
    achievementlink: "",
    attachment: "",
    status: 1,
  },
  imgList: [], // 上传文件列表
  img: null,// 上传文件实例
  file: null, // 上传文件实例
  fileList: [], // 上传文件列表
  dialog: {
    isShowDialog: false,
    type: "",
    title: "",
    submitTxt: "",
    rules: {
      title: [{required: true, message: "请输入", trigger: "blur"}],
      typeId: [{required: true, message: "请输入", trigger: "blur"}],
      userId: [{required: true, message: "请输入", trigger: "blur"}],
      introduction: [{required: true, message: "请输入", trigger: "blur"}],
      img: [{required: true, message: "请选择", trigger: "blur"}]
    }
  }
});
// 打开弹窗
const openDialog = (type: string, row: any, tags: any, users: any) => {
  state.tags = tags;
  state.users = users;
  if (type === "edit") {
    state.dialog.type = "edit";
    state.ruleForm.id = row.id;
    state.ruleForm.userId = row.userId;
    state.ruleForm.title = row.title;
    state.ruleForm.typeId = row.typeId;
    state.ruleForm.introduction = row.introduction;
    state.ruleForm.posterlink = row.posterlink;
    state.ruleForm.achievementlink = row.achievementlink;
    state.ruleForm.attachment = row.attachment;
    state.ruleForm.status = row.status;
    state.imgList = [{url: row.posterlink}];
    console.log(state.imgList);
    state.dialog.title = "编辑成果";
    state.dialog.submitTxt = "保 存";
  } else {
    state.dialog.type = "add";
    state.dialog.title = "新增主页";
    state.dialog.submitTxt = "新 增";
  }
  state.dialog.isShowDialog = true;
};

// 关闭弹窗
const closeDialog = () => {
  state.ruleForm = {
    achievementlink: "",
    attachment: "",
    id: "",
    introduction: "",
    posterlink: "",
    status: 0,
    title: "",
    typeId: "",
    userId: ""
  };
  state.imgList = [];
  state.fileList = [];
  state.dialog.isShowDialog = false;
};

// 取消
const onCancel = () => {
  closeDialog();
};

// 提交
const onSubmit = async (formEl: FormInstance) => {
  await formEl.validate(async (valid, fields) => {
    if (!valid) {
      console.log("error fields: ", fields);
      ElMessage({
        showClose: true,
        message: "完善成果信息",
        type: "error"
      });
    }
    else if (!state.img && !state.ruleForm.posterlink) {
      ElMessage({
        showClose: true,
        message: "请上传封面图片",
        type: "error"
      });
      return;
    } else {
      if (state.file) {
        await qiniu(state.file).then((res: any) => {
          state.ruleForm.attachment = res.key;
        }).catch(() => {
          ElMessage({
            message: "发布失败!!!",
            type: "error"
          });
          return;
        });
      }
      if (state.img) {
        await qiniu(state.img).then((res: any) => {
          state.ruleForm.posterlink = res.key;
        }).catch(() => {
          ElMessage({
            message: "图片上传失败!!!",
            type: "error"
          });
          return;
        });
      }
      if (state.dialog.type === "add") {
        uploadAchievement(state.ruleForm).then(res => {
          closeDialog();
          emit("refresh");
        })
      } else {
        updateAchievement(state.ruleForm).then(res => {
          closeDialog();
          emit("refresh");
        })
      }
    }
  });
};


// 暴露变量
defineExpose({
  openDialog
});
</script>
